<template>
  <el-dialog title="分配权限" :visible="visibleDialog" @close="closeDialog">
    <el-tree
      ref="tree"
      :data="treeData"
      show-checkbox
      default-expand-all
      node-key="id"
      highlight-current
      :props="defaultProps"
      :check-strictly="true"
    />
    <template #footer>
      <el-row type="flex" justify="center">
        <el-button type="" @click.native="closeDialog">取消</el-button>
        <el-button type="primary" @click="confirmPerm">确定</el-button>
      </el-row>
    </template>
  </el-dialog>
</template>

<script>
import { getPermList } from '@/api/permissions'
import { listToTree } from '@/utils/index'
import { updateRoles, getRolesById } from '@/api/roles'
export default {
  props: {
    visibleDialog: {
      type: Boolean,
      required: true
    },
    checkList: {
      type: Array,
      required: true
    },
    curId: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'title'
      }
    }
  },
  created() {
    this.loadPermList()
  },
  methods: {
    // 获取权限列表
    async loadPermList() {
      const res = await getPermList({ _limit: 999 })
      this.treeData = listToTree(res.data, '0')
    },
    // 关闭弹窗
    closeDialog() {
      this.$emit('update:visibleDialog', false)
      // 清空选项
      this.$refs.tree.setCheckedKeys([])
    },

    // 数据回显
    isCheckList() {
      this.$nextTick(() => {
        this.$refs.tree.setCheckedNodes(this.checkList)
      })
    },

    // 确认分配权限
    async confirmPerm() {
      const result = await getRolesById(this.curId)
      // console.log('76', result)
      const newArray = this.$refs.tree.getCheckedNodes()
      // console.log('78', newArray)
      result.data.permissions = newArray
      updateRoles(result.data) // 更新权限
      this.closeDialog() // 关闭弹窗
    }
  }
}
</script>

<style>

</style>
